package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.*;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.IElementPortMtnEvthService;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.service.IElementPortMtnEvthSubService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-mtnevth子接口Controller
 * 
 * @author tony
 * @date 2024-12-24
 */
@Api(tags = "网元-接口-mtnevth子接口")
@RestController
@RequestMapping("/element/port/mtn/evth/sub")
public class ElementPortMtnEvthSubController extends BaseController {
    @Autowired
    private IElementPortMtnEvthSubService elementPortMtnEvthSubService;

    @Autowired
    private IElementPortMtnEvthService elementPortMtnEvthService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 读取网元-接口-mtnevth子接口列表
     */
    @ApiOperation(value = "读取网元-接口-mtnevth子接口列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:sub:list')")
    @GetMapping("/read")
    public TableDataInfo read(ElementPortMtnEvthSub elementPortMtnEvthSub) {
        List<ElementPortMtnEvthSub> elementPortMtnEvthSubs = new ArrayList<>();
        String mtnEvthName = "";
        if (StringUtils.isNotEmpty(elementPortMtnEvthSub.getMtnEvthId())) {
            ElementPortMtnEvth elementPortMtnEvth = elementPortMtnEvthService.selectElementPortMtnEvthById(elementPortMtnEvthSub.getMtnEvthId());
            mtnEvthName = elementPortMtnEvth.getTerminalName();
        }
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">");
        if (StringUtils.isNotEmpty(elementPortMtnEvthSub.getPortName())) {
            xml.append("        <name>").append(mtnEvthName + elementPortMtnEvthSub.getPortName()).append("</name>"); // 子主接口
        }
        xml.append("        <type>ETH-SUBIF</type>" + // 子主接口
//                        "        <enabled>enable</enabled>" + // 子主接口
                "      </interface>" +
                "    </interfaces>" +
                "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortMtnEvthSub.getElementId());
        if (sysConfigService.selectDebugEnabled()) {
            deviceManager.getDevice(netElement.getIp());
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortMtnEvthSub entity = new ElementPortMtnEvthSub();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setPortName(getXmlLabelValue(node, "name"));
//                    entity.setTerminalEnable(getXmlLabelValue(node, "enabled"));
                    entity.setPortDesc(getXmlLabelValue(node, "description"));
                    entity.setTerminalMode(getXmlLabelValue(node, "transport-layer"));
                    entity.setMbps(getXmlLabelValue(node, "bandwidth"));
                    Node ipNode = getXmlLabelNode(node, "ip");
                    entity.setMaxFrameLen(getXmlLabelValue(ipNode, "ipv4-mtu"));
                    Node ipv4AddressListNode = getXmlLabelNode(ipNode, "ipv4-address-list");
                    if (ipv4AddressListNode != null) {
                        String ip = getXmlLabelValue(ipv4AddressListNode, "ipv4-address");
                        entity.setIp(StringUtils.isNotEmpty(ip) ? ip.split("/")[0] : "");
                        entity.setMask(StringUtils.isNotEmpty(ip) ? ip.split("/")[1] : "");
                        entity.setIpForm(getXmlLabelValue(ipv4AddressListNode, "secondry-use"));
                    }
                    Node ifVlan = getXmlLabelNode(node, "if-vlan-cfg");
                    Node switchedNode = getXmlLabelNode(ifVlan, "vlan-sub-cfg");
                    entity.setVlanId(getXmlLabelValue(switchedNode, "svlan_min"));
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementPortMtnEvthSubs.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortMtnEvthSubs);
    }

    /**
     * 查询网元-接口-mtnevth子接口列表
     */
    @ApiOperation(value = "查询网元-接口-mtnevth子接口列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:sub:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortMtnEvthSub elementPortMtnEvthSub) {
        startPage();
        List<ElementPortMtnEvthSub> list = elementPortMtnEvthSubService.selectElementPortMtnEvthSubList(elementPortMtnEvthSub);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-mtnevth子接口列表
     */
    @ApiOperation(value = "导出网元-接口-mtnevth子接口列表", httpMethod = "POST")
//    @PreAuthorize("@ss.hasPermi('net:sub:export')")
    @Log(title = "网元-接口-mtnevth子接口", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortMtnEvthSub elementPortMtnEvthSub) {
        List<ElementPortMtnEvthSub> list = elementPortMtnEvthSubService.selectElementPortMtnEvthSubList(elementPortMtnEvthSub);
        ExcelUtil<ElementPortMtnEvthSub> util = new ExcelUtil<ElementPortMtnEvthSub>(ElementPortMtnEvthSub.class);
        util.exportExcel(response, list, "网元-接口-mtnevth子接口数据");
    }

    /**
     * 获取网元-接口-mtnevth子接口详细信息
     */
    @ApiOperation(value = "获取网元-接口-mtnevth子接口详细信息", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:sub:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortMtnEvthSubService.selectElementPortMtnEvthSubById(id));
    }

    /**
     * 新增网元-接口-mtnevth子接口
     */
    @ApiOperation(value = "新增网元-接口-mtnevth子接口", httpMethod = "POST")
//    @PreAuthorize("@ss.hasPermi('net:sub:add')")
    @Log(title = "网元-接口-mtnevth子接口", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortMtnEvthSub elementPortMtnEvthSub) {
        return toAjax(elementPortMtnEvthSubService.insertElementPortMtnEvthSub(elementPortMtnEvthSub));
    }

    /**
     * 修改网元-接口-mtnevth子接口
     */
    @ApiOperation(value = "修改网元-接口-mtnevth子接口", httpMethod = "PUT")
//    @PreAuthorize("@ss.hasPermi('net:sub:edit')")
    @Log(title = "网元-接口-mtnevth子接口", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortMtnEvthSub elementPortMtnEvthSub) {
        return toAjax(elementPortMtnEvthSubService.updateElementPortMtnEvthSub(elementPortMtnEvthSub));
    }

    /**
     * 删除网元-接口-mtnevth子接口
     */
    @ApiOperation(value = "删除网元-接口-mtnevth子接口", httpMethod = "DELETE")
//    @PreAuthorize("@ss.hasPermi('net:sub:remove')")
    @Log(title = "网元-接口-mtnevth子接口", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortMtnEvthSubService.deleteElementPortMtnEvthSubByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @GetMapping(value = "/activate/{id}")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortMtnEvthSub elementPortMtnEvthSub = elementPortMtnEvthSubService.selectElementPortMtnEvthSubById(id);
        elementPortMtnEvthSub.setStatus("1");
        if (sendXml(elementPortMtnEvthSub)) {
            return toAjax(elementPortMtnEvthSubService.updateElementPortMtnEvthSub(elementPortMtnEvthSub));
        } else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortMtnEvthSub elementPortMtnEvthSub = elementPortMtnEvthSubService.selectElementPortMtnEvthSubById(id);
        elementPortMtnEvthSub.setStatus("1");
        if (sendXml(elementPortMtnEvthSub)) {
            return toAjax(elementPortMtnEvthSubService.updateElementPortMtnEvthSub(elementPortMtnEvthSub));
        } else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementPortMtnEvthSub entity) {
        // TODO: 2024/12/21 待与设备联调
        boolean isSend = true;
        NetElement netElement = netElementService.getCacheObject(entity.getElementId());
        ElementPortMtnEvth elementPortMtnEvth = elementPortMtnEvthService.selectElementPortMtnEvthById(entity.getMtnEvthId());
        StringBuilder xml = new StringBuilder();
        xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                "    <interfaces>" +
                "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                "        <name>" + elementPortMtnEvth.getTerminalName() + "." + entity.getPortName() + "</name>" +
                "        <type>ETH-SUBIF</type>" +
                "        <description>" + entity.getPortDesc() + "</description>" +
                "        <enabled>enable</enabled>" +
                "        <transport-layer xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" + entity.getTerminalMode() + "</transport-layer>" +
                "        <ip xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" +
                "          <ipv4-mtu>" + entity.getMaxFrameLen() + "</ipv4-mtu>" +
                "          <ipv4-address-list>" +
                "            <ipv4-address>" + entity.getIp() + "/" + entity.getMask() + "</ipv4-address>" +
                "            <secondry-use>" + entity.getIpForm() + "</secondry-use>" +
                "          </ipv4-address-list>" +
                "        </ip>" +
                "        <qos-policy-cfgs xmlns=\"http://fiberhome.com/fhnw/yang/qos/fos-qos\"/>" +
                "        <if-vlan-cfg xmlns=\"http://fiberhome.com/fhnw/yang/ethernetservice/fos-vlan\">" +
                "          <termination_type>" + entity.getPackageType() + "</termination_type>" +
                "          <vlan-sub-cfg>" +
                "            <svlan_min>" + entity.getVlanId() + "</svlan_min>" +
                "          </vlan-sub-cfg>" +
                "        </if-vlan-cfg>" +
                "      </interface>" +
                "    </interfaces>" +
                "  </if>");
        System.out.println(xml);

        if (sysConfigService.selectDebugEnabled()) {
            deviceManager.getDevice(netElement.getIp());
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }

        return isSend;
    }
}